/**
 *<p>Copyright: Copyright (c) 2012</p> 
 *<p>Company: SCPII</p>
 *<p>Project:optimus-manage</p>
 *@author xiezhouyan
 *@Date 2013-5-1 下午2:25:53
 *@version 1.0
 *@description:
 */
package com.cybertron.ironhide.manage.util;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.cybertron.ironhide.manage.common.Constants;

public class FileUtil {

	public static final ExecutorService E_SERVICE = Executors
			.newFixedThreadPool(10);

	public static String saveFile(File file, String fileName, boolean resize)
			throws IOException {
		if (file == null || file.length() == 0) {
			return null;
		}
		String resourceRootPath = Constants.RESOURCE_ROOT_PATH;
		String imageFileUploadPrefix = "images";
		String imageExtension = StringUtils.substringAfterLast(fileName, ".");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String dateString = simpleDateFormat.format(new Date());
		String uuid = CommonUtil.getUUID().toLowerCase();
		String parentPath = resourceRootPath + File.separator
				+ imageFileUploadPrefix + File.separator + dateString
				+ File.separator;
		File parentPathFile = new File(parentPath);
		if (!parentPathFile.exists()) {
			parentPathFile.mkdirs();
		}
		File mediaFile = new File(parentPath + uuid + "." + imageExtension);
		if (resize) {
			FileUtils.writeByteArrayToFile(mediaFile,
					ImageUtil.resizeImage(file, Constants.IMAGE_MAX_DIM));
		} else {
			FileUtils.copyFile(file, mediaFile);
		}
		String mediaUrl = "/" + imageFileUploadPrefix + "/" + dateString + "/"
				+ mediaFile.getName();
		return mediaUrl;
	}

	public static String saveFile(File file, String fileName)
			throws IOException {
		return saveFile(file, fileName, true);
	}

	public static String moveAlianceLogoFile(String title, String path) {
		File file = new File(Constants.RESOURCE_ROOT_PATH + path);
		if (!file.exists()) {
			return null;
		}
		String imageExtension = StringUtils.substringAfterLast(file.getName(),
				".");
		String logoPath = "images" + File.separator + "alliance"
				+ File.separator + "logo";
		String logoFileName = DigestUtils.md5Hex(title) + "." + imageExtension;
		File logoFile = new File(Constants.RESOURCE_ROOT_PATH + File.separator
				+ logoPath + File.separator + logoFileName);
		File parnetLogoFile = logoFile.getParentFile();
		if (!parnetLogoFile.exists()) {
			parnetLogoFile.mkdirs();
		}
		try {
			if (!file.equals(logoFile)) {
				if (logoFile.exists()) {
					logoFile.delete();
				}
				FileUtils.copyFile(file, logoFile);
				file.delete();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		String logoUrl = "/images/alliance/logo/" + logoFileName;
		return logoUrl;
	}

	public static String saveFile(String fileUrl, String source) {
		URL url = null;
		String uuid = DigestUtils.md5Hex(fileUrl);
		try {
			url = new URL(fileUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
		String resourceRootPath = Constants.RESOURCE_ROOT_PATH;
		String fileUpadePrefix = "images" + File.separator + source;
		String fileName = StringUtils.substringAfterLast(url.getPath(), "/")
				.toLowerCase();
		String imageExtension = StringUtils.substringAfterLast(fileName, ".");
		String parentPath = resourceRootPath + File.separator + fileUpadePrefix
				+ File.separator;
		File parentPathFile = new File(parentPath);
		if (!parentPathFile.exists()) {
			parentPathFile.mkdirs();
		}
		File savedFile = new File(parentPath + uuid + "." + imageExtension);
		String mediaUrl = "/"
				+ StringUtils.replace(fileUpadePrefix, File.separator, "/")
				+ "/" + savedFile.getName();
		if (savedFile.exists()) {
			return mediaUrl;
		}
		if (url != null) {
			E_SERVICE.execute(new FileUtil().new FileDownloadThread(url,
					savedFile, false));
		}
		return mediaUrl;
	}

	public class FileDownloadThread implements Runnable {

		private final URL url;

		private final File savedFile;

		private final boolean resize;

		public FileDownloadThread(URL url, File savedFile, boolean resize) {
			super();
			this.url = url;
			this.savedFile = savedFile;
			this.resize = resize;
		}

		@Override
		public void run() {
			File parentFile = savedFile.getParentFile();
			File tmpFile = new File(parentFile.getAbsolutePath()
					+ File.separator + CommonUtil.getUUID() + ".tmp");
			try {
				FileUtils.copyURLToFile(url, tmpFile);
				if (tmpFile.exists()) {
					if (resize) {
						ImageUtil.resizeImage(tmpFile, Constants.IMAGE_MAX_DIM);
					}
					FileUtils.copyFile(tmpFile, savedFile);
					tmpFile.delete();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
